import Data.List (maximumBy, sortBy, reverse)

type Time = Integer
type ID = Integer

type Condition = (Time, ID)

splitAll :: Eq a => [a] -> [a] -> [[a]]
splitAll _ [] = []
splitAll delims xs = 
    token : splitAll delims rest
    where
        isDelimiter = (`elem` delims)
        token       = takeWhile (not . isDelimiter) xs
        rest        = dropWhile isDelimiter $ dropWhile (not . isDelimiter) xs

parseInput :: String -> (Condition, [Condition])
parseInput string = (maxCondition, conditions')
    where
        conditions = map (\(t,id) -> (t,read id))
                   . filter ((/="x") . snd) 
                   . zip [0..]
                   . splitAll ","
                   . last 
                   . lines $ string 

        maxCondition = maximumBy cmp conditions
        
        conditions' = reverse . sortBy cmp . filter (/=maxCondition) $ conditions

        cmp :: Condition -> Condition -> Ordering
        cmp (_,id1) (_,id2) = id1 `compare` id2

obeyCondition :: Condition -> Time -> Bool
obeyCondition (time, id) timestamp = (timestamp + time) `mod` id == 0

obeyConditions :: [Condition] -> Time -> Bool
obeyConditions conditions timestamp = all (\c -> obeyCondition c timestamp) conditions

solute :: (Condition, [Condition]) -> Time
solute ((time, id), conditions) = 
    head . filter (obeyConditions conditions) $ timestamps
    where            
        startTime = (100000000000000 `div` id + 1) * id - time
        timestamps = [startTime, startTime+id..]

main :: IO ()
main = do
    input <- readFile "input.txt"
    print . solute . parseInput $ input